<?php

namespace app\controllers\h5\uni;

use app\controllers\h5\base\H5Controller;
use app\models\Material as Model;
use app\util\Util;

class MaterialController extends H5Controller
{
    public function actionList()
    {
        $page = intval($this->post('page', $this->page));
        $pageSize = intval($this->post('pageSize', $this->pageSize));

        $query = Model::find()
            ->where(['status' => Model::$statusMapping['OK']]);

        $totalCount = $query->count();
        $totalPage = ceil($totalCount / $pageSize);

        $list = $query->orderBy(['sort' => SORT_ASC, 'id' => SORT_DESC])
            ->offset(($page - 1) * $pageSize)
            ->limit($pageSize)
            ->asArray()
            ->all();

        foreach ($list as &$item) {
            $convert = Util::convertImages($item['content']);
            // var_dump($convert);exit;
            $item['inImages'] = $convert['images'];
            $item['inText'] = $convert['text'];
            unset($item['content']);

            $item['time'] = date('Y-m-d', strtotime($item['create_time']));

            // 去除文字中的p标签
            $item['inTextNew'] = str_replace(['<p>', '</p>'], "\n", $item['inText']);
            $item['inTextNew'] = str_replace("\n\n", "\n", $item['inTextNew']);
            $item['inTextNew'] = str_replace("\n\n", "\n", $item['inTextNew']);
            $item['inTextNew'] = str_replace("<br />", "", $item['inTextNew']);
            // var_dump($item);exit;

        }

        return $this->successEncode([
            $this->list => $list,
            $this->totalCount => (int)$totalCount,
            $this->totalPage => $totalPage,
            $this->currentPage => $page
        ]);

    }
}